<template>
  <el-dialog
    v-model="userInfoVisible"
    :title="mode === 'add' ? '新增用户' : '编辑用户'"
    width="500px"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="right"
      label-width="100px"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" clearable :disabled="mode === 'edit'" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password" clearable show-password />
      </el-form-item>
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="formData.type">
          <el-option label="普通用户" value="common" />
          <el-option label="交通部门用户" value="traffic" />
          <el-option label="管理员" value="admin" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="userInfoVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ submitting ? '提交中...' : '确认' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const formRef = ref(null)
const formData = ref({ username: '', password: '', type: 'common' })
const submitting = ref(false)

const formRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
}

const props = defineProps({
  modelValue: Boolean,
  currentUser: Object,
  mode: String,
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const userInfoVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

// 监听当前用户变化
watch(
  () => props.currentUser,
  (user) => {
    if (user && props.mode === 'edit') {
      formData.value = {
        username: user.username,
        password: user.password,
        type: user.type,
      }
    } else {
      formData.value = {
        username: '',
        password: '',
        type: 'common',
      }
    }
  },
  { immediate: true },
)

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const token = localStorage.getItem('token')
    const config = { headers: { Authorization: `Bearer ${token}` } }

    if (props.mode === 'add') {
      await axios.post('http://localhost:3001/adduser', { userObj: formData.value }, config)
      ElMessage.success('用户添加成功')
    } else {
      await axios.put(
        'http://localhost:3001/updateuser',
        {
          id: props.currentUser.id,
          userObj: formData.value,
        },
        config,
      )
      ElMessage.success('用户信息更新成功')
    }

    userInfoVisible.value = false
    emit('refresh')
  } catch (error) {
    if (error.response?.data?.message === 'USERNAME_EXISTS') {
      ElMessage.error('用户名已存在')
    } else {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 22px;
}
</style>
